from ..models.parking_space import ParkingSpace
from ..extensions import db
from ..utils.response import success, error, pagination


def create_parking_space(data):
    """创建车位"""
    # 验证必填字段
    if not data.get('location'):
        return error('车位不能为空', 400)
    
    # 创建车位
    parking_space = ParkingSpace(
        location=data['location'],
        carPlate=data.get('carPlate'),
        feeValidityPeriod=data.get('feeValidityPeriod')
    )
    
    try:
        db.session.add(parking_space)
        db.session.commit()
        return success(parking_space.to_dict(), '创建成功')
    except Exception as e:
        db.session.rollback()
        return error('创建失败', 500)


def get_parking_spaces(data):
    """获取车位列表，支持按位置、车牌筛选，支持分页"""
    query = ParkingSpace.query
    
    # 按位置筛选
    if data.get('location'):
        query = query.filter(ParkingSpace.location.like(f"%{data['location']}%"))
    
    # 按车牌筛选
    if data.get('carPlate'):
        query = query.filter(ParkingSpace.carPlate.like(f"%{data['carPlate']}%"))
    
    # 按费用有效期筛选
    if data.get('feeValidityPeriod'):
        query = query.filter(ParkingSpace.feeValidityPeriod.like(f"%{data['feeValidityPeriod']}%"))
    
    # 按用户ID筛选
    if data.get('user_id'):
        query = query.filter(ParkingSpace.user_id == data['user_id'])
    
    # 计算总数
    total = query.count()
    
    # 按创建时间倒序排序
    query = query.order_by(ParkingSpace.created_at.desc())
    
    # 获取分页参数
    page = int(data.get('page', 1))
    page_size = int(data.get('page_size', 10))
    
    # 处理无效的分页参数
    if page < 1:
        page = 1
    if page_size < 1:
        page_size = 10
    elif page_size > 100:
        page_size = 100  # 限制最大每页记录数
    
    # 计算偏移量
    offset = (page - 1) * page_size
    
    # 获取分页数据
    parking_spaces = query.offset(offset).limit(page_size).all()
    
    # 返回分页数据
    return pagination(
        items=[parking_space.to_dict() for parking_space in parking_spaces],
        total=total,
        msg='获取成功',
        code=200
    )


def get_parking_space(parking_space_id):
    """获取单个车位信息"""
    # 查找车位
    parking_space = ParkingSpace.query.get(parking_space_id)
    
    if not parking_space:
        return error('车位不存在', 404)
    
    return success(parking_space.to_dict(), '获取成功')


def update_parking_space(data):
    """更新车位信息"""
    # 获取车位ID
    parking_space_id = data.get('id')
    if not parking_space_id:
        return error('车位ID不能为空', 400)
    
    # 查找车位
    parking_space = ParkingSpace.query.get(parking_space_id)
    if not parking_space:
        return error('车位不存在', 404)
    
    # 更新字段
    if 'location' in data:
        if not data['location']:
            return error('车位不能为空', 400)
        parking_space.location = data['location']
    
    if 'carPlate' in data:
        parking_space.carPlate = data['carPlate']
    
    if 'feeValidityPeriod' in data:
        parking_space.feeValidityPeriod = data['feeValidityPeriod']
    
    try:
        db.session.commit()
        return success(parking_space.to_dict(), '更新成功')
    except Exception as e:
        db.session.rollback()
        return error('更新失败', 500)


def delete_parking_space(parking_space_id):
    """删除车位"""
    # 查找车位
    parking_space = ParkingSpace.query.get(parking_space_id)
    
    if not parking_space:
        return error('车位不存在', 404)
    
    try:
        db.session.delete(parking_space)
        db.session.commit()
        return success({}, '删除成功')
    except Exception as e:
        db.session.rollback()
        return error('删除失败', 500)